require "net"
require "sim"
require "config"
require "log"
require "ril"
require "ntp"
module(..., package.seeall)

local msgQuene = {}

local function ismgJson(topic, payload, qos, user)
    local jsonstr = json.encode(payload)
    table.insert(msgQuene, {t = topic, p = jsonstr, q = qos, user = user})
end

function hwInstertMsg(topic, payload)
    ismgJson(topic, payload, 0, {cb = pubSysInfoOneCb})
end

local function pubSysInfoOneCb(result) end
-- 初始启动

function waitForSend() return #msgQuene > 0 end

function proc(mqttClient)
    while #msgQuene > 0 do
        -- local outMsg = table.remove(msgQuene, 1)
        local outMsg = msgQuene[1]
        local result = mqttClient:publish(outMsg.t, outMsg.p, outMsg.q)
        if result then table.remove(msgQuene, 1) end
        log.info("SEND RESULT", result)
        log.info("SEND TOPIC", outMsg.t)
        log.info("SEND DATA", outMsg.p)
        local count = 0

        if outMsg.user and outMsg.user.cb then
            outMsg.user.cb(result, outMsg.user.para)
        end
        if not result then return end
    end
    return true
end

function unInit()
    sys.publish("HW_MQTT_CUSTOM_TASK_KILL")
    while #msgQuene > 0 do
        local outMsg = table.remove(msgQuene, 1)
        if outMsg.user and outMsg.user.cb then
            outMsg.user.cb(false, outMsg.user.para)
        end
    end
end

